package com.ruoyi.framework.config;

import com.alibaba.fastjson.JSONArray;
import com.ruoyi.framework.cache.config.CacheServiceFactory;
import com.ruoyi.framework.cache.service.CacheService;
import com.ruoyi.framework.util.RedisUtils;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.service.ISysDictDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 初始化缓存
 * 
 * @author lh
 */
@Configuration
public class InitCacheConfig implements CommandLineRunner {

    protected final Logger logger = LoggerFactory.getLogger(InitCacheConfig.class);

    private static final String SYS_CACHE = "sysCache";

    public static final String CACHE_DICT_MAP = "dictMap";

    public static final String CACHE_INDUSTRY_MAP = "industryMap";

    public static final String CACHE_INDUSTRY_LIST = "industryList";

    public static final String CACHE_DISTCODE_MAP = "distCodeMap";

    public static final String CACHE_DIST_LIST = "distList";

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private CacheServiceFactory cacheServiceFactory;

    public void refreshDictCache(){
        logger.info("==========================字典缓存加载开始==========================");
        List<SysDictData> dicts = dictDataService.selectDictDataAllList();
        cacheServiceFactory.getCacheService().removeAll(InitCacheConfig.CACHE_DICT_MAP);
        if(dicts!=null && dicts.size()>0){
            String dictType = dicts.get(0).getDictType();
            JSONArray array = new JSONArray();
            for (SysDictData dict : dicts){
                if (!dictType.equals(dict.getDictType())) {
                    cacheServiceFactory.getCacheService().put(InitCacheConfig.CACHE_DICT_MAP, dictType, array.toString());
                    array.clear();
                    dictType = dict.getDictType();
                }
                array.add(dict);
            }
            cacheServiceFactory.getCacheService().put(InitCacheConfig.CACHE_DICT_MAP, dictType, array.toString());
        }
        logger.info("==========================字典缓存加载成功==========================");
    }

    @Override
    public void run(String... args) throws Exception {
        refreshDictCache();
    }
}